package com.pocketsweet.ui.fragments;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.lidroid.xutils.ViewUtils;
import com.pocketsweet.MLApplication;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.RandomCallMatchingActivity;
import com.pocketsweet.model.MLTopic;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.Main;
import com.pocketsweet.ui.OnlineTestLoverActivity;
import com.pocketsweet.ui.SignInRecord;
import com.pocketsweet.ui.Splash;
import com.pocketsweet.ui.Topic;
import com.pocketsweet.ui.TopicActivity;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.HeaderLayout.onRightContainerListener;
import com.pocketsweet.ui.uilib.MyPagerGalleryView;
import com.pocketsweet.ui.uilib.MyPagerGalleryView.MyOnItemClickListener;
import com.pocketsweet.ui.uilib.adapter.AdvertiseAdapter;
import com.pocketsweet.ui.uilib.adapter.AdvertiseAdapter.ViewHolder_advertise;

public class ExploreFragment extends Fragment implements View.OnClickListener,
        OnItemClickListener {
    private View rootView;
    private static Context mContext;
    private RelativeLayout relTestLover;
    private RelativeLayout relWhisper;
    private TextView tv23CallMatchOpenTime;
    private RelativeLayout relLoverCall;
    private RelativeLayout relSign;
    private MyPagerGalleryView adgallery;
    private LinearLayout ovalLayout;
    private AdvertiseAdapter advertiseAdapter;
    public static List<MLTopic> advertiseList = new ArrayList<MLTopic>();

    private boolean hidden;
    private boolean isCallMatch = false;
    private boolean isTimeOver = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_explore, null);
        ViewUtils.inject(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mContext = getActivity();
        initView();
    }

    private void initView() {
        relTestLover = (RelativeLayout) getActivity().findViewById(
                R.id.relTestLover);
        relWhisper = (RelativeLayout) getActivity().findViewById(
                R.id.relWhisper);
        relLoverCall = (RelativeLayout) getActivity().findViewById(
                R.id.relLoverCall);
        relSign = (RelativeLayout) getActivity().findViewById(
                R.id.relSign);
        tv23CallMatchOpenTime = (TextView) getActivity().findViewById(
                R.id.tv23CallMatchOpenTime);
        adgallery = (MyPagerGalleryView) getActivity().findViewById(
                R.id.adgallery);
        ovalLayout = (LinearLayout) getActivity().findViewById(R.id.ovalLayout);
        advertiseAdapter = new AdvertiseAdapter(getActivity(), advertiseList);
        adgallery.setAdapter(advertiseAdapter);
        relTestLover.setOnClickListener(this);
        relWhisper.setOnClickListener(this);
        relLoverCall.setOnClickListener(this);
        relSign.setOnClickListener(this);
    }

    /*
     * 加载列表
     */
    private void getRecommendList() {
        if (advertiseList == null || advertiseList.size() <= 0) { // userList为空或者动作为下拉刷新、往下加载时请求leanCloud
            final AVQuery<MLTopic> queryTopic = new AVQuery<MLTopic>("MLTopic");
            queryTopic.orderByDescending("priority"); // 按照优先级排序
            queryTopic.whereEqualTo("status", 1); // 状态为发布
            queryTopic.findInBackground(new FindCallback<MLTopic>() {
                public void done(List<MLTopic> mlTopic, AVException e) {
                    if (e == null) {
//						Log.e("getTopic成功", "查询到" + mlTopic.size()
//								+ " 条符合条件的数据" + mlTopic.toString());
                        if (mlTopic.size() > 0) {
                            advertiseList = mlTopic;
                            // adgallery.notify();
                            advertiseAdapter = new AdvertiseAdapter(getActivity(), advertiseList);
                            adgallery.setAdapter(advertiseAdapter);
                            advertiseAdapter.notifyDataSetChanged();
//							Main.clearRecommendRecord();
                        }
                        // linBlank.setVisibility(View.GONE);

                        // articleListview
                        // .setSelection(skipDataCount);
                        // recommendArticleListAdapter
                        // .setDatas(advertiseList);
                        // recommendArticleListAdapter
                        // .notifyDataSetChanged();
                    } else {
//						Log.e("getTopic失败", "查询错误: " + e.getMessage());
                        getRecommendList(); // 重新加载
                        // linBlank.setVisibility(View.VISIBLE);
                    }
                }
            });
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        this.hidden = hidden;
        if (!hidden) {
            // refresh();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (UserService.getCurrentUser() == null) {
            Intent intent = new Intent(getActivity().getApplicationContext(),
                    Splash.class);
            PendingIntent restartIntent = PendingIntent.getActivity(
                    getActivity().getApplicationContext(), 0, intent,
                    Intent.FLAG_ACTIVITY_NEW_TASK);
            AlarmManager mgr = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
            mgr.set(AlarmManager.RTC, System.currentTimeMillis(),
                    restartIntent);
            MLApplication mlApplication = MLApplication.getInstance();
            mlApplication.finishActivity();
        }
        if (UserService.getCurrentUser() == null) {
            System.exit(0);
            Intent intent = new Intent(getActivity(), Splash.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                    | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
        advertiseAdapter.notifyDataSetChanged();
        if (advertiseList == null || advertiseList.size() <= 0) {
            getRecommendList();
        }
        isCallMatch = is23ClockMatch();
        if (isCallMatch == true) {
            tv23CallMatchOpenTime.setText(getResources().getString(
                    R.string.explore_23call_match_opening));
        } else {
            tv23CallMatchOpenTime.setText(getResources().getString(
                    R.string.explore_23call_match_unopen));
        }
        if (!hidden) {
            //
        }
    }

    public static void setHeaderFunction() {
        HeaderLayout header = Main.getInstance().getHeader();
        header.setRighttContainerClickListener(new onRightContainerListener() {

            @Override
            public void onClick() {
            }
        });

        header.setLeftContainerClickListener(new onLeftContainerListener() {

            @Override
            public void onClick() {

            }
        });
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.relTestLover:
                Intent testLoverIntent = new Intent(getActivity(),
                        OnlineTestLoverActivity.class);
                getActivity().startActivity(testLoverIntent);
                AVAnalytics.onEvent(Main.getInstance(), "点击实习恋人");
                break;
            case R.id.relWhisper:
                isCallMatch = is23ClockMatch();
                if (isCallMatch == true) {
                    Intent intent = new Intent(getActivity(),
                            RandomCallMatchingActivity.class);
                    getActivity().startActivity(intent);
                    Main.rlNightWhisper.setVisibility(View.GONE);
                } else if (isTimeOver == false) {
                    Main.rlNightWhisper.setVisibility(View.VISIBLE);
//				ToolKits.toast(getActivity(), "还没到23点哦");
                } else if (isTimeOver == true) {
                    Main.rlNightWhisper.setVisibility(View.VISIBLE);
//				ToolKits.toast(getActivity(), "已经超过23点了哦");
                }
                // Intent intent = new Intent(getActivity(),
                // RandomCallMatchingActivity.class);
                // getActivity().startActivity(intent);
                AVAnalytics.onEvent(Main.getInstance(), "深夜秘语");
                break;
            case R.id.relLoverCall:
                Main.rlLoverInvited.setVisibility(View.VISIBLE);
                AVAnalytics.onEvent(Main.getInstance(), "情感热线点击（发现页）");
                break;
            case R.id.relSign:
                Intent relSignIntent = new Intent(getActivity(),
                        SignInRecord.class);
                getActivity().startActivity(relSignIntent);
                //			AVAnalytics.onEvent(Main.getInstance(), "情感热线点击（发现页）");
                break;
        }
    }

    private boolean is23ClockMatch() {
        SimpleDateFormat formatters = new SimpleDateFormat("HH:mm");
        Date curDates = new Date(System.currentTimeMillis());// 获取当前时间
        String strs = formatters.format(curDates);
        System.out.println(strs);
        // // 开始时间
        // int startHour = 11;// 小时
        // int startMin = 11;// 分
        // // 结束时间
        // int endHour = 23;// 小时
        // int endMin = 41;// 分
        // 开始时间
        int startHour = 23;// 小时
        int startMin = 11;// 分
        // 结束时间
        int endHour = 23;// 小时
        int endMin = 41;// 分

        String[] dds = new String[]{};

        // 分取系统时间 小时分
        dds = strs.split(":");
        int curHour = Integer.parseInt(dds[0]);
        int curMin = Integer.parseInt(dds[1]);
        // Log.e("==cur",
        // "现在是：" + String.valueOf(curHour) + ":" + String.valueOf(curMin));

        // if (startHour <= curHour && curHour <= endHour) {
        // if (startHour == curHour && startMin >= curMin) {
        // Intent intent = new Intent(getActivity(),
        // RandomCallMatchingActivity.class);
        // getActivity().startActivity(intent);
        // } else if (curHour == endHour && endMin <= curMin) {
        // Intent intent = new Intent(getActivity(),
        // RandomCallMatchingActivity.class);
        // getActivity().startActivity(intent);
        // } else {
        // ToolKits.toast(getActivity(), "不在时间范围内哦");
        // }
        // } else {
        // ToolKits.toast(getActivity(), "不在时间范围内哦");
        // }

        if (startHour <= curHour && curHour <= endHour) {
            if (startHour < curHour && curHour < endHour) {
                // Intent intent = new Intent(getActivity(),
                // RandomCallMatchingActivity.class);
                // getActivity().startActivity(intent);
                return true;
                // Log.e("==cur", "现在是：1");
            } else if (startHour == curHour && startMin <= curMin
                    && endMin >= curMin) {
                // Intent intent = new Intent(getActivity(),
                // RandomCallMatchingActivity.class);
                // getActivity().startActivity(intent);
                return true;
                // Log.e("==cur", "现在是：2");
            } else if (curHour == endHour && startMin <= curMin
                    && endMin > curMin) {
                // Intent intent = new Intent(getActivity(),
                // RandomCallMatchingActivity.class);
                // // Log.e("==cur", "现在是：3");
                // getActivity().startActivity(intent);
                return true;

            } else if (curHour == endHour && curMin > endMin) {
                isTimeOver = true;
                // ToolKits.toast(getActivity(), "已经超过23点了哦");
                // Log.e("==cur", "现在是：4");
            } else if (curHour == startHour && startMin <= curMin
                    && curHour < endHour) {
                // Intent intent = new Intent(getActivity(),
                // RandomCallMatchingActivity.class);
                // // Log.e("==cur", "现在是：8");
                // getActivity().startActivity(intent);
                return true;
            } else {
                isTimeOver = false;
                // ToolKits.toast(getActivity(), "还没到23点哦");
                // Log.e("==cur", "现在是：5");
            }
        } else if (startHour > curHour) {
            isTimeOver = false;
            // ToolKits.toast(getActivity(), "还没到23点哦");
            // Log.e("==cur", "现在是：6");
        } else if (endHour < curHour) {
            isTimeOver = true;
            // ToolKits.toast(getActivity(), "已经超过23点了哦");
            // Log.e("==cur", "现在是：7");
        }
        return false;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        ViewHolder_advertise viewHolder_advertise = advertiseAdapter.new ViewHolder_advertise();
        viewHolder_advertise.gallery
                .setMyOnItemClickListener(new MyOnItemClickListener() {
                    public void onItemClick(int curIndex) {
                        switch (advertiseList.get(curIndex).getType()) {
                            case 0:
                                Intent intent = new Intent(getActivity(),
                                        Topic.class);
                                intent.putExtra("topic", advertiseList
                                        .get(curIndex).getObjectId().toString());
                                intent.putExtra("title", advertiseList
                                        .get(curIndex).getTitle());
                                getActivity().startActivity(intent);

                                break;
                            case 1:
                                Intent intent1 = new Intent(getActivity(),
                                        TopicActivity.class);
                                intent1.putExtra("title",
                                        advertiseList.get(curIndex).getTitle());
                                intent1.putExtra("url", advertiseList.get(curIndex)
                                        .getAddress());
                                getActivity().startActivity(intent1);
                                break;
                        }

                    }
                });
        AVAnalytics.onEvent(getActivity(), "专题活动");
    }

}
